<?php
use app\common\model\User;
use app\common\model\UserBill;
use app\common\model\UserRechargeRule;
use think\facade\Log;


/**
 * 用户事件
 * Class OrderSubscribe
 * @package crmeb\subscribes
 */
class UserSubscribe
{
	
	/**
    * 用户会员充值成功
    * @param array $event
     */
    public function onVipRechargeSuccess($info)
    {
    	//添加到账户
    	$uid = $info['uid'];
    	$price = floatval($info['price']);
    	
    	$user = User::get($uid);
    	
    	//获取赠送规则
    	$rule = UserRechargeRule::where('status',0)
    		->where("shop_id", $user->shop_id )
    		->where('price','<=',$price)
    		->where(function ($query) {
	    		$query->where(function ($query)  {
					$query->whereNull('expire_time');
				});
				$query->whereor(function ($query)  {
					$query->whereNotNull('expire_time');
					$query->where([['','exp',\Db::raw("date_format(now(),'%Y-%m-%d %H:%i:%s') < expire_time")]]);
				});
			})->order('price desc')->limit(1)->findOrEmpty();
    	
    	//获取赠送项
    	$giveBalance = $rule['balance_gift'] ?? 0;
    	$giveIntegral= $rule['integral_gift'] ?? 0;
    	
    	$user->balance = ['inc', $price];
    	$user->balance_gift = ['inc', $giveBalance];
    	$user->integral = ['inc', $giveIntegral];
    	$user->save();
    	
    	//添加流水账
    	$mark = '会员充值入账'.$price.'元';
    	UserBill::income("会员充值",$uid,'balance','recharge',$price,$info['no'],0,$mark);
    	if($giveBalance){
    		$mark= '会员充值赠送'.$giveBalance.'余额';
    		UserBill::income("会员充值",$uid,'balance_gift','gain',$giveBalance,$info['no'],0,$mark);
    	}
    	if($giveIntegral){
    		$mark= '会员充值赠送'.$giveIntegral.'积分';
    		UserBill::income("会员充值",$uid,'integral','gain',$giveIntegral,$info['no'],0,$mark);
    	}
    	
		return true;
    }
	
}